package com.kedacom.ctsp.authority.controller;

import com.kedacom.ctsp.authority.constant.AccessLoggerConstant;
import com.kedacom.ctsp.authority.entity.*;
import com.kedacom.ctsp.authority.service.*;
import com.kedacom.ctsp.authority.vo.ChargeRelationVO;
import com.kedacom.ctsp.authz.entity.Authentication;
import com.kedacom.ctsp.authz.exception.UnauthorizedException;
import com.kedacom.ctsp.lang.StringUtil;
import com.kedacom.ctsp.logging.AccessLogger;
import com.kedacom.ctsp.web.controller.AbstractCrudController2;
import com.kedacom.ctsp.web.controller.message.ResponseMessage;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Set;


/**
 * 分管关系关联管理
 *
 * @author sunchenjie
 */
@ResponseBody
@RequestMapping("charge_relation")
@AccessLogger(AccessLoggerConstant.Module.CHARGE_RELATION)
@Api(tags = "ChargeRelation", description = "分管关系关联管理")
public class AuthorityChargeRelationController extends AbstractCrudController2<ChargeRelation, String, ChargeRelationVO, ChargeRelationService> {

    @Autowired
    private DataDictService dataDictService;

    @Autowired
    private PersonService personService;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public ResponseMessage<String> add(@RequestBody ChargeRelationVO data) {

        //检查添加分管，请求参数有效
        if (!checkAddChargeRelationRequestParam(data)) {
            return ResponseMessage.error(StringUtil.format("auth.charge.relation.request.param.error"));

        }

        //TODO 添加添加分管，规则(人->人 不能分管级别比自己高的人;人->部门 下级部门的人不能分管上级部门)
//        String checkAddData = checkAddChargeRelationData(data);
//        if (StringUtils.isNotBlank(checkAddData)) {
//            return ResponseMessage.error(StringUtil.format(checkAddData));
//        }

        return super.add(data);

    }

    /**
     * 添加添加分管，规则
     *
     * @param data
     * @return
     */
    private String checkAddChargeRelationData(ChargeRelationVO data) {

        //添加分管的操作人，只能操作自己有权限的人的和部门
        Authentication authentication = Authentication.current().orElseThrow(UnauthorizedException::new);
        //操作人员所在部门的人员id
        List<String> authDeptPersonIds = personService.getPersonIdsByDeptCode(authentication.getPerson().getDeptCode());
        if (authDeptPersonIds == null) {
            return "auth.charge.relation.request.param.error";
        }

        //分管人员
        Person fromPerson = personService.get(data.getIdFrom());
        if (fromPerson == null) {
            return "auth.charge.relation.request.param.error";
        }
        //分管人的userId
        String fromUserId = personService.getUserIdByPersonId(data.getIdFrom());
        if (StringUtils.isBlank(fromUserId)) {
            return "auth.charge.relation.request.param.error";
        }

        if (!authDeptPersonIds.contains(data.getIdFrom())//
                && !authentication.getPerson().getChargedUsers().contains(fromUserId)) {
            //不能操作，权利之外部门的人
            return "auth.charge.relation.request.param.error";
        }

        // 人->人
        if (StringUtils.equals(data.getTypeFrom(), String.valueOf(SettingForType.PERSON.ordinal()))
                && StringUtils.equals(data.getTypeTo(), String.valueOf(SettingForType.PERSON.ordinal()))) {

            //被分管人员
            Person toPerson = personService.get(data.getIdTo());
            if (toPerson == null) {
                return "auth.charge.relation.request.param.error";
            }
            //被分管人的userId
            String toUserId = personService.getUserIdByPersonId(data.getIdTo());
            if (StringUtils.isBlank(toUserId)) {
                return "auth.charge.relation.request.param.error";
            }

            if (!authDeptPersonIds.contains(data.getIdTo())//
                    && !authentication.getPerson().getChargedUsers().contains(toUserId)) {
                //不能操作，权利之外部门的人
                return "auth.charge.relation.request.param.error";
            }

            //TODO 没有人员级别，不能分管级别比自己高的人
            return "";
        }

        // 人->部门
        if (StringUtils.equals(data.getTypeFrom(), String.valueOf(SettingForType.PERSON.ordinal()))
                && StringUtils.equals(data.getTypeTo(), String.valueOf(SettingForType.DEPARTMENT.ordinal()))) {

            //被分管部门
            Department toDepartment = departmentService.get(data.getIdTo());
            if (toDepartment == null) {
                return "auth.charge.relation.request.param.error";
            }

            //操作人，下级、分管部门
            Set<String> authDeptCodes = authentication.getPerson().getCascadedAndChargedDeptCodes();
            if (!authDeptCodes.contains(toDepartment.getCode())) {
                //操作人，权利范围之外的部门，不可操作
                return "auth.charge.relation.request.param.error";
            }

            if (fromPerson.getDepartment().getPath().indexOf(toDepartment.getPath()) >= 0) {
                //分管人员部门，是被分管部门的子部门，下级部门的人不能分管上级部门
                return "auth.charge.relation.person.level.error";
            }
        }
        return "";
    }


    /**
     * 检查添加分管参数
     *
     * @param data
     * @return
     */
    private boolean checkAddChargeRelationRequestParam(ChargeRelationVO data) {
        if (StringUtils.isBlank(data.getChargeType())//
                || StringUtils.isBlank(data.getTypeFrom())//
                || StringUtils.isBlank(data.getTypeTo())//
                || StringUtils.isBlank(data.getIdTo())//
                || StringUtils.isBlank(data.getIdFrom())
                ) {
            return false;
        }

        //检查分管方式（只允许 人->人，人->部门）
        if ((!(StringUtils.equals(data.getTypeFrom(), String.valueOf(SettingForType.PERSON.ordinal()))
                && StringUtils.equals(data.getTypeTo(), String.valueOf(SettingForType.PERSON.ordinal()))))//
                && (!(StringUtils.equals(data.getTypeFrom(), String.valueOf(SettingForType.PERSON.ordinal()))
                && StringUtils.equals(data.getTypeTo(), String.valueOf(SettingForType.DEPARTMENT.ordinal()))))) {
            return false;
        }

        //检查类型
        DataDict dataDict = dataDictService.findByCode(data.getChargeType());
        if (dataDict == null) {
            return false;
        }
        return true;
    }

}